package org.smart4j.chapter1.util;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Created by wangzhen on 2018/4/12.
 */
public final class DatabaseHelper {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseHelper.class);
    private static final QueryRunner QUERY_RUNNER = new QueryRunner();
    private static final ThreadLocal<Connection> CONNECTION_THREAD_LOCAL = new ThreadLocal<Connection>();
    private static final String DRIVER = "";
    private static final String URL = "";
    private static final String USER = "";
    private static final String PWD = "";

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            logger.error("未找到数据库驱动类！！！");
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection() {
        Connection conn = CONNECTION_THREAD_LOCAL.get();
        if(conn==null) {
            try {
                conn = DriverManager.getConnection(URL, USER, PWD);
            } catch (SQLException e) {
                logger.error("获取数据库连接失败！！！");
                e.printStackTrace();
            } finally {
                CONNECTION_THREAD_LOCAL.set(conn);
            }
        }
        return conn;
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection() {
        Connection conn = CONNECTION_THREAD_LOCAL.get();
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("关闭数据库连接失败！！！");
                e.printStackTrace();
            } finally {
                CONNECTION_THREAD_LOCAL.remove();
            }
        }
    }

    /**
     * 查询实体类list
     * @param EntityClass
     * @param sql
     * @param params
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> EntityClass, String sql, Object ... params) {
        List<T> EntityList = null;
        Connection connection = getConnection();
        try {
            EntityList = QUERY_RUNNER.query(connection, sql, new BeanListHandler<T>(EntityClass), params);
        } catch (SQLException e) {
            logger.error("查询数据出错！！！");
            e.printStackTrace();
        } finally {
            closeConnection();
        }
        return EntityList;
    }

}
